import { WebSocket } from "ws";
import { Game } from "./game/Game";
import { GameConn } from "./game/player/GameConn";
import { KProto } from "./game/proto/KProto";

export class Conn extends GameConn {

    constructor(
        game: Game,
        public ws: WebSocket
    ) {
        super();

        ws.binaryType = "arraybuffer";
        ws.onmessage = e => {
            if (e.data instanceof ArrayBuffer) {
                //协议通信
                const protoId = KProto.decodeId(new Uint8Array(e.data));
                const data = KProto.decodeTos(protoId as any);
                this.onProto(protoId as any, data);
            }
        }

        game.onConn(this, pid => {
            ws.onclose = e => {
                game.removePlayer(pid);
            }
        });
    }

    send<ID extends KProtoTocNeed>(protoId: ID, data: KProtoToc[ID]): void;
    send<ID extends KProtoTocNever>(protoId: ID): void;
    send(protoId: KProtoId, data?: any): void {
        KProto.encodeId(protoId);
        this.ws.send(KProto.encodeToc(protoId as any, data));
    }

}